package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.*;
import com.lhdx.practical.config.UploadConfig;
import com.lhdx.practical.dao.MenuDao;
import com.lhdx.practical.service.PersonService;
import com.lhdx.practical.service.StudentGroupService;
import com.lhdx.practical.service.TaskService;
import com.lhdx.practical.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/function/task")
public class TaskController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private TaskService taskService;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private PersonService personService;
    @Autowired
    private StudentGroupService studentGroupService;
    @Autowired
    private UploadConfig uploadConfig;

    /**
     * 学生作业列表
     * @param mid
     * @param sid
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(long mid,long sid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        List<Task> mytask = taskService.findAllByAuthoridAndTypeAndSidAndMidAndGradeid(userid,0,sid,mid,person.getGradeid());
        List<Task> grouptask = taskService.findAllByTypeAndSidAndMidAndGradeid(1,sid,mid,person.getGradeid());
        return new ModelAndView("task/list")
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("mytask",mytask)
                .addObject("grouptask",grouptask);
    }

    @GetMapping("/teacherList")
    public ModelAndView teacherList(long mid,long sid,long gradeid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<Task> pageResult = new PageVo<Task>(page,searchmap,taskService.getResultList(mid,sid,gradeid,0,page,Constants.pagesize));
        return new ModelAndView("task/teacherList")
                .addObject("pageResult",pageResult)
                .addObject("menu",menu)
                .addObject("gradeid",gradeid)
                .addObject("smenu",smenu);
    }

    @GetMapping("/teacherGroupList")
    public ModelAndView teacherGroupList(long mid,long sid,long gradeid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<StudentGroup> pageResult = new PageVo<StudentGroup>(page,searchmap,studentGroupService.getResultList(0,2,gradeid,page,Constants.pagesize));
        JSONArray array = new JSONArray();
        JSONObject json = null;
        List<Task> tasks = null;
        for(StudentGroup studentGroup : pageResult.getList()){
            json = new JSONObject();
            json.put("id",studentGroup.getId()+"");
            json.put("groupname",studentGroup.getGroupname());
            tasks = taskService.findAllByGroupidAndType(studentGroup.getId(),1);
            json.put("upsize",tasks.size());
            array.add(json);
        }
        return new ModelAndView("task/teacherGroupList")
                .addObject("pageResult",pageResult)
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("gradeid",gradeid)
                .addObject("array",array);
    }

    @GetMapping("/grouptask")
    public ModelAndView grouptask(long groupid,long mid,long sid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        StudentGroup group = studentGroupService.findById(groupid);
        List<Task> tasks = taskService.findAllByGroupidAndType(groupid,1);
        return new ModelAndView("task/grouptask")
                .addObject("group",group)
                .addObject("tasks",tasks)
                .addObject("menu",menu)
                .addObject("smenu",smenu);
    }

    @GetMapping("/add")
    public ModelAndView add(long mid,long sid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        return new ModelAndView("task/add")
                .addObject("menu",menu)
                .addObject("smenu",smenu);
    }

    @GetMapping("/update")
    public ModelAndView update(long id) {
        Task task = taskService.findById(id);
        Menu menu = menuDao.findById(task.getMid());
        Menu smenu = menuDao.findById(task.getSid());
        return new ModelAndView("task/update")
                .addObject("task",task)
                .addObject("menu",menu)
                .addObject("smenu",smenu);
    }

    /**
     * 上传作业
     * @param
     * @return
     */
    @CrossOrigin
    @PostMapping("addTask")
    @ResponseBody
    public String addTask(long id,long mid,long sid,int type,String title,String attachments,String detail) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            int count = taskService.countAllBySidAndType(sid,type);
            //类型 0个人作业 1小组作业 个人作业只允许有一次
            List<Task> tasks = null;
            Task task;
            if(type == 0){
                tasks = taskService.findAllByAuthoridAndTypeAndSidAndMidAndGradeid(person.getId(),type,sid,mid,person.getGradeid());
                if(tasks.size() == 0){
                    task = new Task(0,mid,sid,person.getGradeid(),type,person,title,attachments,detail,count+1);
                    taskService.save(task);
                }else{
                    task = tasks.get(0);
                    task.setTitle(title);
                    task.setAttachments(attachments);
                    task.setDetail(detail);
                    task.setCreatetime(new Date().getTime());
                    taskService.save(task);
                }
            }else{
                //小组作业任意上传
                if(id == 0){
                    task = new Task(0,mid,sid,person.getGradeid(),type,person,title,attachments,detail,count+1);
                }else{
                    task = taskService.findById(id);
                    task.setTitle(title);
                    task.setAttachments(attachments);
                    task.setDetail(detail);
                    task.setCreatetime(new Date().getTime());
                }

                taskService.save(task);
            }
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"作业上传成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"作业上传失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 上传作业
     * @param
     * @return
     */
    @CrossOrigin
    @PostMapping("deleteTask")
    @ResponseBody
    public String deleteTask(long id) {
        JSONObject jsonObject = new JSONObject();
        try {
            taskService.deleteById(id);
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"作业删除成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"作业删除失败","");
        }
        return jsonObject.toString();
    }

    //上传作业
    @CrossOrigin
    @PostMapping("uploadTask")
    @ResponseBody
    public String uploadTask(@RequestParam("file") MultipartFile file,String mname,int type) {
        JSONObject jsonObject = new JSONObject();
        if (!file.isEmpty()) {
            String url = "";
            try {
                long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                Person person = personService.findById(userid);
                fileName = mname + "-";
                if(type == 0){
                    fileName += person.getRealname()+"个人作业";
                }else{
                    fileName += person.getGroupname() + "-" + person.getRealname() + "小组作业";
                    List<Task> tasks = taskService.findAllByGroupidAndType(person.getGroupid(),type);
                    fileName += tasks.size()+1;
                }
                url = "/files/"+fileName + "."+ suffix;
                FileUtil.uploadFile(file.getBytes() , uploadConfig.getUploadPath()+"/files/", fileName + "."+ suffix);
            } catch (Exception e) {
                e.printStackTrace();
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"文件上传失败","");
            }
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"上传成功",url);
        } else {
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"文件不存在","");
        }
        return jsonObject.toJSONString();
    }
}
